<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\helper\ConfigHelper;
use app\common\library\helper\Helper;
use app\common\model\Config;
use app\common\model\Heavy_fog;
use app\common\model\Tide;
use app\common\model\TideInfo;
use app\common\model\MessageLog;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 天气
 */
class Weather extends Api
{

    // 时间
    public $time;
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->time = $this->request->get('time') ?: date('Y-m-d');
    }

    public function weatherList()
    {
        $cityid = $this->request->get('cityid');
        $wxTemplate = ConfigHelper::getConfig('wxTemplate');
        $weather = ConfigHelper::getConfig('weather');
        $result = file_get_contents($weather['url'] . '?version=v1&appid=' . $weather['appid'] . '&appsecret=' . $weather['appsecret'] . '&cityid=' . $cityid);
        $result = json_decode($result, true);
        $data = $result['data'];
        $data = array_column($data, null, 'date');
        if (isset($data[date('Y-m-d')])) {
            $data = $data[date('Y-m-d')];
        } else {
            return $this->error('暂未改记录');
        }
        $start = strtotime('today');
        $end = strtotime(date('Y-m-d 23:59:59'));
        $find = MessageLog::getInstance()->whereBetween('time', $start . "," . $end)->order('id desc')->limit(1)->find();
//        $wind_scale = 7;
//        $wind_towards = '东南';
//        $hours = '05';
        $wind_scale = 0;
        $wind_towards = '';
        $hours = '';
        foreach ($data['hours'] as $value) {
            if (empty($find)) {
                // 东南风达到6级或者所有风向达到7级需要推送
                if (($value['win'] == '东南风' && strpos($value['win_speed'], '6'))) {
                    $wind_scale = 6;
                    $wind_towards = '东南风';
                    $hours = $value['hours'];
                    break;
                } elseif (strpos($value['win_speed'], '7')) {
                    $wind_scale = 7;
                    $wind_towards = $value['win'];
                    $hours = $value['hours'];
                    break;
                }
            } else {
                $length = strlen($value['win_speed']);
                for ($i = 0; $i < $length; $i++) {
                    if ($value['win_speed'][0] > $find['wind_scale']) {
                        $wind_scale = $value['win_speed'][$i];
                        $wind_towards = $value['win'];
                        $hours = $value['hours'];
                        break;
                    }
                }
                if ($wind_scale) {
                    break;
                }
            }
        }
//        if ($wind_scale == 0) {
//            return $this->error('暂无大风力');
//        }
//        //需要开启事务,避免出现垃圾数据
//        Db::startTrans();
//        try {
//            $id = MessageLog::getInstance()->insertGetId([
//                'time' => time(),
//                'wind_scale' => $wind_scale,
//                'wind_towards' => $wind_towards,
//                'createtime' => time()
//            ]);
//            Db::commit();
//        } catch (Exception $e) {
//            Db::rollback();
//            return false;
//        }
//        // 添加成功执行推送
//        if ($id) {
//            $number = Heavy_fog::getInstance()->sendMessage([
//                'template_id' => $wxTemplate['badWeather'],
//                'data' => [
//                    'first' => ['value' => '风力预警', 'color' => '#FF0000'],
//                    'keyword1' => ['value' => '今天风力会在' . $hours . '达到' . $wind_scale . '级大风', 'color' => '#173177'],
//                    'keyword2' => ['value' => date('Y-m-d H:i:s'), 'color' => '#173177'],
//                    'remark' => ['value' => Config::getInstance()->where(['id' => 20])->value('value'), 'color' => '#FF0000']
//                ]
//            ]);
//            if ($number > 0) {
//                $this->error($number . '条发送失败');
//            } else {
//                $this->success('发送成功', 'gale/index');
//            }
//        }
        $this->success('操作成功', $result);
    }

    // 获取潮汐列表
    public function getList()
    {
        $data = Tide::getInstance()->where('day_time', '=', $this->time)->find();
        if ($data) {
            $data = $data->toArray();
            unset($data['id'], $data['day_time']);
            $data = array_values($data);
        }
        return $this->success('获取成功', $data);
    }

    // 获取潮汐高潮与低潮列表
    public function tidalList()
    {
        $data = TideInfo::getInstance()->where('day_time', '=', $this->time)->find();
        $res = [];
        if ($data) {
            $data = $data->toArray();
            unset($data['id'], $data['day_time']);
            $res = [
                ['time' => $data['time_1'], 'height' => $data['height_1']],
                ['time' => $data['time_2'], 'height' => $data['height_2']],
                ['time' => $data['time_3'], 'height' => $data['height_3']],
                ['time' => $data['time_4'], 'height' => $data['height_4']],
            ];
        }
        return $this->success('获取成功', $res);
    }

    // 获取潮汐最大时间
    public function maxTime()
    {
        $time = Tide::getInstance()->order('day_time desc')->value('day_time');
        if ($time) {
            $time = date('Y-m-d', strtotime($time));
        }
        $this->success('获取成功', ['maxTime' => $time ?: '']);
    }

    public function test()
    {
        $cityid = $this->request->get('cityid');
        $wxTemplate = ConfigHelper::getConfig('wxTemplate');
        $weather = ConfigHelper::getConfig('weather');
        $result = file_get_contents($weather['url'] . '?version=v1&appid=' . $weather['appid'] . '&appsecret=' . $weather['appsecret'] . '&cityid=' . $cityid);
        $result = json_decode($result, true);
        $data = $result['data'];
        $data = array_column($data, null, 'date');
        if (isset($data[date('Y-m-d')])) {
            $data = $data['2021-07-24'];
        } else {
            return $this->error('暂未改记录');
        }

        $start = strtotime('today');
        $end = strtotime(date('Y-m-d 23:59:59'));
        $find = MessageLog::getInstance()->whereBetween('time', $start . "," . $end)->order('id desc')->limit(1)->find();
        // 记录风力最大等级
        $wind_scale = 0;
        // 记录风向
        $wind_towards = is_array($data['win']) ? $data['win'] : explode(',', $data['win']);
        // 取风力最大的值
        $length = strlen($data['win_speed']);
        $arr = [];
        for ($i = 0; $i < $length; $i++) {
            if(is_numeric($data['win_speed'][$i])) {
                $arr[] = $data['win_speed'][$i];
            }
        }
        $max = max($arr);
        // 东南风达到6级或者所有风向达到7级需要推送
        if($find) {
            $wind_scale = $max > $find['wind_scale'] ? $max : 0;
        } else {
            if((in_array('东南风', $wind_towards) && $max >= 6) || $max >= 7) {
                $wind_scale = $max;
            }
        }
        if ($wind_scale == 0) {
            $this->error('暂无大风力');
        }
        //需要开启事务,避免出现垃圾数据
//        Db::startTrans();
//        try {
//            MessageLog::getInstance()->insertGetId([
//                'time' => time(),
//                'wind_scale' => $wind_scale,
//                'wind_towards' => json_encode($wind_towards),
//                'createtime' => time()
//            ]);
//            Db::commit();
//        } catch (ValidateException | PDOException | Exception $e) {
//            Db::rollback();
//            return false;
//        }
        // 添加成功执行推送
        Heavy_fog::getInstance()->sendMessage([
            'template_id' => $wxTemplate['badWeather'],
            'data' => [
                'first' => ['value' => '风力预警', 'color' => '#FF0000'],
                'keyword1' => ['value' => '风力等级' . $data['win_speed'], 'color' => '#173177'],
                'keyword2' => ['value' => date('Y-m-d H:i:s'), 'color' => '#173177'],
                'remark' => ['value' => Config::getInstance()->where(['id' => 20])->value('value'), 'color' => '#FF0000']
            ]
        ]);
        $this->success('操作成功', $data);
    }
}
